package com.hkyl.hospital.service.impl;

import com.github.pagehelper.PageHelper;
import com.hkyl.hospital.entity.Role;
import com.hkyl.hospital.entity.User;
import com.hkyl.hospital.entity.UserExample;
import com.hkyl.hospital.mapper.UserMapper;
import com.hkyl.hospital.mapper.custom.CustomUserMapper;
import com.hkyl.hospital.service.RoleService;
import com.hkyl.hospital.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gao
 * @date 2023/07/09 11:24:57
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private CustomUserMapper userMapper;
    @Autowired
    private RoleService roleService;
    @Override
    public int save(User user) {
        int i = userMapper.insertSelective(user);

        return i;
    }

    @Override
    public int update(User user) {
        int i = userMapper.updateByPrimaryKeySelective(user);
        return i;
    }

    @Override
    public List<User> findAll() {
        List<User> users = userMapper.selectByExample(null);
        return users;
    }

    @Override
    public User findOne(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        List<Role> roleIdsByUserId = roleService.findRoleIdsByUserId(id);
        user.setRoles(roleIdsByUserId);
        return user;
    }

    @Override
    public int delete(Integer id) {
        int i = userMapper.deleteByPrimaryKey(id);
        return i;
    }

    @Override
    public List<User> findSomeByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        return userMapper.selectByExample(null);
    }

    @Override
    public int distributeRoles(Integer userId, List<Integer> roles) {
        int i = userMapper.clearUserRoles(userId);
        if(roles.size()>0){
            i += userMapper.distributeUserRoles(userId, roles);
        }
        return i;
    }

    @Override
    public List<User> selectByDeptId(Integer deptId,Integer pageNumber,Integer pageSize) {
        UserExample userExample = new UserExample();
        userExample.or().andDeptIdEqualTo(deptId);
        List<User> users = userMapper.selectByExample(userExample);
        return users;
    }
}
